package com.lanchetech.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.lanchetech.common.util.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class OSSClientUtil {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.bucket}")
    private String bucket;
    @Value("${oss.bucketName}")
    private String bucketName;
    @Value("${oss.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.http}")
    private String ossHttp;
    private OSSClient ossClient;

    @PostConstruct
    public void init() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    public void destory() {
        ossClient.shutdown();
    }

    /**
     * 上传文件到OSS
     *
     * @param file
     * @return
     * @throws Exception
     */
    public String uploadFile(MultipartFile file) throws Exception {
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        // 为了避免被人遍历读取图片，图片的命名必须无规则
        String name = ThreadContext.generateRequestUUID() + substring;
        // 文件按日分目录保存
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String folder = dateFormat.format(new Date()) + "/";
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, name, folder);
            return ossHttp + bucket + "/" + folder + name;
        } catch (Exception e) {
            throw new Exception("文件上传失败");
        }
    }

    /**
     * 上传文件到OSS
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String uploadWebImage(String url) throws Exception {
        String substring = ".png";
        // 为了避免被人遍历读取图片，图片的命名必须无规则
        String name = ThreadContext.generateRequestUUID() + substring;
        // 文件按日分目录保存
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String folder = dateFormat.format(new Date()) + "/";
        try {
            BufferedImage image = ImageIO.read(new URL(url));
            //判断宽高最大的一个值
            int max=Math.max(image.getHeight(), image.getWidth());
            BufferedImage outImage =  new BufferedImage(max, max,BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = outImage.createGraphics();
            outImage = graphics2D.getDeviceConfiguration().createCompatibleImage(max, max, Transparency.TRANSLUCENT);
            graphics2D.dispose();
            graphics2D = outImage.createGraphics();
            //原图高度
            int oldheight = image.getHeight();
            //原图宽度
            int oldwidth = image.getWidth();
            // 设置图片居中显示
            graphics2D.drawImage(image, (max - oldwidth) / 2,(max - oldheight) / 2, null);
            graphics2D.dispose();
            //生成新的图片
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(outImage, "png", os);
            InputStream inputStream = new ByteArrayInputStream(os.toByteArray());

            ossClient.putObject(bucketName, folder + name, inputStream);
            return ossHttp + bucket + "/" + folder + name;
        } catch (Exception e) {
            throw new Exception("文件上传失败");
        }
    }

    /**
     * 上传文件到OSS 按视频尺寸
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String uploadWebImageOriginally(String url) throws Exception {
        String substring = ".png";
        // 为了避免被人遍历读取图片，图片的命名必须无规则
        String name = ThreadContext.generateRequestUUID() + substring;
        // 文件按日分目录保存
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String folder = dateFormat.format(new Date()) + "/";
        try {
            BufferedImage image = ImageIO.read(new URL(url));
            BufferedImage outImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = outImage.createGraphics();
            outImage = graphics2D.getDeviceConfiguration().createCompatibleImage(image.getWidth(), image.getHeight(), Transparency.TRANSLUCENT);
            graphics2D.dispose();
            graphics2D = outImage.createGraphics();
            graphics2D.drawImage(image, 0, 0, null);
            graphics2D.dispose();
            //生成新的图片
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(outImage, "png", os);
            InputStream inputStream = new ByteArrayInputStream(os.toByteArray());

            ossClient.putObject(bucketName, folder + name, inputStream);
            return ossHttp + bucket + "/" + folder + name;
        } catch (Exception e) {
            throw new Exception("文件上传失败");
        }
    }



    /**
     * 上传到OSS服务器 如果同名文件会覆盖服务器上的
     *
     * @param inStream 文件流
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String uploadFile2OSS(InputStream inStream, String fileName, String folder) {
        String ret = "";
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getContentType(fileName));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            // 上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName, folder + fileName, inStream, objectMetadata);
            ret = putResult.getETag();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param fileName 文件后缀
     * @return String
     */
    public static String getContentType(String fileName) {
        String FilenameExtension = fileName.substring(fileName.lastIndexOf("."));
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "application/x-bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xla") ||
                FilenameExtension.equalsIgnoreCase(".xlc")||
                FilenameExtension.equalsIgnoreCase(".xlm")||
                FilenameExtension.equalsIgnoreCase(".xls")||
                FilenameExtension.equalsIgnoreCase(".xlt")||
                FilenameExtension.equalsIgnoreCase(".xlw")) {
            return "application/vnd.ms-excel";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        if (FilenameExtension.equalsIgnoreCase(".pdf")) {
            return "application/pdf";
        }
        if (FilenameExtension.equalsIgnoreCase(".zip")) {
            return "application/zip";
        }
        if (FilenameExtension.equalsIgnoreCase(".tar")) {
            return "application/x-tar";
        }
        if (FilenameExtension.equalsIgnoreCase(".avi")) {
            return "video/avi";
        }
        if (FilenameExtension.equalsIgnoreCase(".mp4")) {
            return "video/mpeg4";
        }
        if (FilenameExtension.equalsIgnoreCase(".mp3")) {
            return "audio/mp3";
        }
        if (FilenameExtension.equalsIgnoreCase(".mp2")) {
            return "audio/mp2";
        }
        if (FilenameExtension.equalsIgnoreCase(".wav")) {
            return "audio/wav";
        }
        return "application/octet-stream";
    }

}
